import type { RouterContext } from "@koa/router";
import { BaseController } from "./common";
import type { AuthLoginRequest, AuthRegisterRequest } from "@/types/api";
import {
  isset,
  passwordValidator,
  usernameValidator,
} from "../utils/validator";
import { container } from "../services/register";
import { JWTPayload } from "@/services/vendor/jsonwebtoken";

export default class AuthController extends BaseController {
  async login(ctx: RouterContext) {
    const body = this.getBody<AuthLoginRequest>(ctx);
    this.assert(isset(body?.username), 1, "用户名必填");
    this.assert(isset(body?.password), 2, "密码必填");
    this.assert(usernameValidator(body.username), 3, "用户名格式错误");
    this.assert(passwordValidator(body.password), 4, "密码格式错误");
    return container.resolve("AuthService").login(body);
  }
  async register(ctx: RouterContext) {
    const body = this.getBody<AuthRegisterRequest>(ctx);
    this.assert(isset(body?.username), 1, "用户名必填");
    this.assert(isset(body?.password), 2, "密码必填");
    this.assert(usernameValidator(body.username), 3, "用户名格式错误");
    this.assert(passwordValidator(body.password), 4, "密码格式错误");
    return container.resolve("AuthService").register(body);
  }
  async profile(ctx: RouterContext) {
    const payload = this.getUser<JWTPayload>(ctx);
    return container.resolve("UserService").profile(payload.userId);
  }
}
